
package com.lagou.service.impl;

import com.lagou.api.ICodeService;
import com.lagou.api.IUserService;
import com.lagou.dao.UserTokenDao;
import com.lagou.pojo.UserToken;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Created by wangq on 2021/9/26.
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserTokenDao userTokenDao;

//    @Autowired
//    CodeFeignClient codeFeignClient;

    @Reference
    ICodeService iCodeService;

    @Override
    public Integer register(HttpServletResponse response, String email, String password, String code) {
        // 邮箱是否注册过
        if (isRegistered(email)) {
            return 1;
        }
        // 验证码是否有效
        Integer validate = iCodeService.validate(email, code);
        if (validate != 0) {
            return 2;
        }
        // 更新或者保存token
        UserToken userToken = createOrUpdateToken(email);

        // 添加token到cookie
        Cookie cookie = new Cookie("token", userToken.getToken());
        cookie.setDomain("www.test.com");
        cookie.setPath("/");
        response.addCookie(cookie);
        return 0;
    }

    private UserToken createOrUpdateToken(String email) {
        String token = UUID.randomUUID().toString();
        // 查询是否存在token
        UserToken oldToken = userTokenDao.findByEmail(email);
        // 如果存在，就更新token
        if (oldToken != null) {
            oldToken.setToken(token);
            userTokenDao.saveAndFlush(oldToken);
            return oldToken;
        }
        // 如果不存在就新建
        UserToken userToken = new UserToken(email, token);
        userTokenDao.save(userToken);
        return userToken;
    }

    @Override
    public Boolean isRegistered(String email) {
        UserToken userToken = userTokenDao.findByEmail(email);
        return userToken != null;
    }

    @Override
    public String login(HttpServletResponse response, String email, String password) {
        if (!checkPassword(email, password)) {
            return "账号密码错误";
        }
        // 更新或者保存token
        UserToken userToken = createOrUpdateToken(email);

        // 添加token到cookie
        Cookie cookie = new Cookie("token", userToken.getToken());
        cookie.setDomain("www.test.com");
        cookie.setPath("/");
        response.addCookie(cookie);

        return userToken.getEmail();
    }

    private boolean checkPassword(String email, String password) {
        return true;
    }

    @Override
    public String info(String token) {
        UserToken userToken = userTokenDao.findByToken(token);
        if (userToken == null) {
            return "";
        }
        return userToken.getEmail();
    }
}